import React, { useState, useRef, useEffect } from "react";
import { User, Menu, Icon, IconContent, UserName } from "./styled";
import dataManager from "@/utils/dataManager";
import indexedDBManager from "@/utils/indexedDB";
import { message } from "antd";
import { useNavigate } from "react-router-dom";
const userAvatar = ({ state, dispatch }) => {
  const { isShowUserMeun } = state;
  const [avatar, setAvatar] = useState(localStorage.getItem("avatar") || '');
  const [name, setName] = useState(localStorage.getItem("userName") || '用户');
  const navigate = useNavigate();
  const handleClick = (e) => {
    e.stopPropagation(); // 防止事件冒泡
    e.preventDefault(); // 防止默认事件
    dispatch({
      type: "setState",
      payload: {
        isShowUserMeun: true,
        isShowSupplyMeun: false,
      },
    });
  };
  // 上传之后
  useEffect(() => {
    if (avatar) {
      localStorage.setItem("avatar", avatar);
    }
  }, [avatar]);

  // 监听localStorage变化
  useEffect(() => {
    const updateUserInfo = () => {
      setAvatar(localStorage.getItem("avatar") || '');
      setName(localStorage.getItem("userName") || '用户');
    };

    // 监听storage变化
    window.addEventListener('storage', updateUserInfo);

    return () => {
      window.removeEventListener('storage', updateUserInfo);
    };
  }, []);

  const logOut = async () => {
    try {
      await dataManager.logout();

      dispatch({
        type: "setState",
        payload: {
          isShowUserMeun: false,
          isLogin: false,
          isRegister: false,
          isSeelpClick: false,
          isWinModelVisiable: false,
          barIconData: [],
          iframeList: [],
          isdeskTopLoading: true,
          loadingTips: "关闭桌面应用中...",
        },
      });

      setTimeout(() => {
        localStorage.clear();
        dispatch({
          type: "setState",
          payload: {
            loadingTips: "清除缓存中...",
          },
        });
      }, 1000);

      setTimeout(() => {
        dispatch({
          type: "setState",
          payload: {
            isdeskTopLoading: false,
            isNotlockScreen: false,
          },
        });
        navigate("/index");
      }, 3000);
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  const updateAvatarHandleClick = () => {
    let input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.onchange = async function () {
      let file = this.files[0];
      if (!file) return;

      try {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const base64 = e.target.result;
          const currentUser = await dataManager.getCurrentUser();

          if (currentUser) {
            // 保存图片到数据库
            const image = await indexedDBManager.saveImage({
              uid: currentUser.uid,
              name: file.name,
              data: base64,
              type: file.type,
              size: file.size
            });

            // 更新用户头像
            await dataManager.updateUser({ avatar: base64 });
            setAvatar(base64);
          }
        };
        reader.readAsDataURL(file);
      } catch (error) {
        message.error('头像上传失败');
        console.error('Upload avatar failed:', error);
      }
    };
    input.click(); // 模拟手动点击
  };

  // 导入数据
  const importData = () => {
    let input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", ".json");
    input.onchange = async function () {
      let file = this.files[0];
      if (!file) return;

      try {
        await dataManager.importData(file);
        message.success('数据导入成功，请刷新页面');
      } catch (error) {
        message.error('数据导入失败');
        console.error('Import data failed:', error);
      }
    };
    input.click();
  };

  // 导出数据
  const exportData = async () => {
    try {
      await dataManager.exportData();
    } catch (error) {
      message.error('数据导出失败');
      console.error('Export data failed:', error);
    }
  };

  // 修复图标路径
  const fixIconPaths = async () => {
    try {
      const success = await dataManager.fixIconPaths();
      if (success) {
        message.success('图标修复成功，请刷新页面');
        // 刷新页面以应用新的图标路径
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      }
    } catch (error) {
      message.error('图标修复失败');
      console.error('Fix icon paths failed:', error);
    }
  };

  // 清除所有数据
  const clearAllData = async () => {
    try {
      const success = await dataManager.clearAllData();
      if (success) {
        message.success('数据清除成功，返回登录页面');
        // 清除完成后返回登录页面
        setTimeout(() => {
          window.location.href = '/index';
        }, 1000);
      }
    } catch (error) {
      message.error('数据清除失败');
      console.error('Clear all data failed:', error);
    }
  };

  return (
    <User onClick={handleClick}>
      <IconContent>
        <Icon src={avatar || "/img/default/user.svg"} alt="用户头像" />
      </IconContent>
      <UserName>{name}</UserName>
      {isShowUserMeun && (
        <Menu>
          <Menu.item onClick={updateAvatarHandleClick}>修改头像</Menu.item>
          <Menu.item onClick={exportData}>导出数据</Menu.item>
          <Menu.item onClick={importData}>导入数据</Menu.item>
          <Menu.item onClick={fixIconPaths}>修复图标</Menu.item>
          <Menu.item onClick={clearAllData}>重置数据</Menu.item>
          <Menu.item onClick={logOut}>注销</Menu.item>
        </Menu>
      )}
    </User>
  );
};

export default userAvatar;
